var list_datas=new Array();
var datas_ggmc=new Array();
var datas_sm=new Array();
var datas_muls=new Array();
var project_data={};
var jt_datas=[]; 
var jump_datas = [];
var clamp_length_datas=[];
var clamp_length2_datas=[];
var my_gx=[];
var treefilm;
var jtss=[];
var list_index;
var info;

var projectOld = null;
var edit_jtss=[];
var edit_project_data={};
var edit_jt_datas=[]; 
var edit_ggss=[];// used
var edit_cn=[];// used
var edit_xms2 = {// used
    "project_id": "",
    "project_name": "",
    "project_code": "",
    "process_data": [   
    ]
  };


webix.ready(function(){
	var operators = JSON.parse($("#operators").val());
 var cutters = JSON.parse($("#cutters").val());
  var machines = JSON.parse($("#machines").val());
  var materielstr = ""; 
   for (var i = 0; i < cutters.data.length; i++) {  
	  if(materielstr.indexOf(cutters.data[i].value)<0){
		  materielstr+=cutters.data[i].customer_specs_no+","; 
	  }    
}
 
  materielstr = materielstr.substring(0,materielstr.length-1);
  var materielArr =  materielstr.split(",");
  var materiels = [];
  for (var i = 0; i < materielArr.length; i++) {
	  var materiel = {};
	  materiel["id"]=materielArr[i];
	  materiel["value"]=materielArr[i];
	  materiels[materiels.length] = materiel;
}
 

  // ---------------------- 添加项目模态框开始------------------
  // 模态框的form表单内容
  var add_P_form = {
    view:"form",
    id:"add_P_form",
    borderless:true,
    complexData:true,
    elements: [
      { 
        margin:20,
        cols:[
          {view:"text",label:"项目名称",id:"project_name",name:"project_name",width:300,labelWidth:100},
          { 
			  
	            view : "datepicker",
	            id : "start_date",
	            timepicker : true,
	            label : "开始日期",
	            labelAlign : "right",
	            name : "start",
	            stringResult : true,
	            format : "%Y-%m-%d",
	            width : 240
	          },
	          {
	            view : "datepicker",
	            id : "end_date",
	            timepicker : true,
	            label : "结束日期",
	            labelAlign : "right",
	            name : "end",
	            stringResult : true,
	            format : "%Y-%m-%d ",
	            width : 240
	          }, 
        ]
      },{
    	  cols:[{
	        	   view:"multiselect",
	   		    id:"operators", 
	   		    width:700,
	   		    labelWidth:320,
	   		    label:"装刀人员选择(若无集中装刀需求可不选)", 
	   		    yCout:2,
	   		    options:{
	   		      data:operators.data 
	   		    },
    	  }
    		  ]
    	  
      },
      {
        margin:10,
        cols:[
          {},
          {view:"button",id:"btn4",value:'下一步',click:"down_pro",inputWidth:70,width:70}
        ]
      }
    ]
  } 
  var add_P_toolbar={
    view:"toolbar",
    id:"add_P_toolbar",
    elements:[     
      {view:"label", label: "添加项目",width:85},
      {},
      { view:"icon", icon:"times-circle", css:"alter",click:"$$('project').hide();"}
    ], 
  }
 // window模态框
  var project=new webix.ui({
    view:"window",
    id:'project',
    width:1200,
    position:"center",
    modal:true,
    move:true,
    head:webix.copy(add_P_toolbar),
    body:webix.copy(add_P_form)
  });
 // ---------------------- 添加项目模态框结束------------------
 
  // ---------------------- 添加工序、规格（寿命）、机台模态框开始------------------
  
  /* 显示工序添加操作 */
  var pro_list={
    rows:[
      { margin:10,
        cols:[
          {
            view:"text",
            id:"add_pro",
            label:"工序名称:",
            placeholder:"请输入要添加的工序名称",
            width:210
          },
          {
            view:"button",
            id:"add_pros_btn",
            width:70,
            value:"添加工序",
            click:"add_pros"
          }
        ]
      },
      {
        view:"text",
        id:"search_pro",
        label:"快速查找:",
        placeholder:"请输入工序名称进行查询",
        width:270
      },
      {
        view:"list",         
        id:"process_list",         
        template:"#process_name#<button class='delbtn1 right2 style'>删除</button>",
        width:270,
        height:400,
        select:true,
        data:[],
        onClick: {// 删除工序事件
          "delbtn1": function(e, id, trg) {
            var list_index2=$$("process_list").getIndexById(id);// 点击的删除按钮所在工序索引
            if (xms2.process_data[list_index]) { // 判断数据是否已经保存过，若保存过还需将数据删除
              $$("process_list").remove(id);// 删除相应界面
              xms2.process_data.splice(list_index2,1); // 删除相应工序数据
              ggss.splice(list_index2,1); // 删除相应规格寿命数据
              jt_datas.splice(list_index2,1); // 删除相应机台数据
              /* 更换规格界面 */
              $$("my_pro_dt").clearAll();
              var id2 = $$("process_list").getSelectedId(); // 相应界面删除后，若焦点更换，获取其id
              var list_index3=$$("process_list").getIndexById(id2);
              $$("my_pro_dt").define("data",ggss[list_index3] );
              $$("my_pro_dt").refresh();
              /* 更换机台界面 */           
              $$("muls").setValue(jt_datas[list_index3]);
              $$("muls").refresh();
            } 
            else {
              $$("process_list").remove(id);
            }
            return false;
            // here it blocks default behavior
          }
        },
      }  
  ]};
  /* 规格表格 */
  var my_pro_dt={
    view:"datatable",
    id:"my_pro_dt",  
    width:800, 
    height:440, 
    columns:[
      {id:"material_id",header:"物料编码/规格全称",width:350,options:cutters.data,suggest:{
        body:{
          on:{
            'onItemClick':function(id){
              // 获取整个工序的规格gg_values,并判断规格是否为重
              var dt=$$("my_pro_dt");
              
              var sel2 = dt.getSelectedId();// 获取正在选择的行的行id,列id名称,和行id
              var row2 = dt.getItem(sel2.row);// 获取正在选择的行的行内容,列内容,和行id
              row2.add_cutter_code=id;
              
              var gg_value;
              var gg_values=[];
              var select_value=this.getItem(id).value;
              dt.eachRow( function (row){               
                gg_value=dt.getText(row,"material_id");
                gg_values.push(gg_value);                            
              });
              //
              for(var i = 0; i < gg_values.length; i++) {
                if(select_value==gg_values[i]){
                  webix.alert({
                    title:"警告",
                    text:"同一规格不能添加两次，如果需要添加，请在刀具库中添加新规格，通过客户简称区别！",
                    ok:"确定", 
                    type:"confirm-warning",
                    callback:function(result){
                      if(result==true){
                        var sel = dt.getSelectedId();// 获取正在选择的行的行id,列id名称,和行id
                        var row = dt.getItem(sel.row);// 获取正在选择的行的行内容,列内容,和行id
                        row.material_id="";
                        row.add_cutter_code="";
                        dt.updateItem(sel.row, row);                       
                      }
                    }
                  }); 
                  break;
                }
              };
            }
          }
        }
      }},
      {id:"cutter_life",header:"寿命",editor:"text",width:70},
      {id:"add_cutter_code",header:"编码",width:150,hidden:true},
      {id:"is_replace",header:"选为替换",width:100,template:"{common.checkbox()}"},

      {
          id: "operate",
          header: "操作",
          width: 70,
          tooltip: false,
          fillspace: true,
          template: "<button class='delbtn2 style'>删除</button>"
      }/* {common.trashIcon()}删除 */
    ],  
    onClick: {// 删除规格寿命事件
      "delbtn2": function(e, id, trg) {// list_index指选中的工序
        var id2 = $$("process_list").getSelectedId(); // 相应界面删除后，若焦点更换，获取其id
        var list_index=$$("process_list").getIndexById(id2);// 焦点所在工序索引
        var list_index2=$$("my_pro_dt").getIndexById(id);// 焦点所在规格寿命索引
        if (xms2.process_data[list_index]) { // 判断数据是否已经保存过，若保存过还需将数据删除
          ggss[list_index].splice(list_index2,1); // 删除相应规格寿命数据
          $$("my_pro_dt").editStop();
          $$("my_pro_dt").remove(id);         
        }
        else{
          $$("my_pro_dt").editStop();
          $$("my_pro_dt").remove(id); 
        }
        return false;
      } 
    },     
    select:true,
    data:"",
    editable:true,
    tooltip:true
    // data:filmset,//url:当是外来数据时用这个
    // url:"http://192.168.1.111:9001/Application/demo"
  };
  /* 添加一行规格按钮 */
  var add_button={
    view:"button",value:"添加物料",width:100,click:"addRows"
  };
  var add_materiel={
		    view:"multicombo",
		    id:"materiels", 
		    width:300,
		    inputWidth:300,
 		    yCout:2,
		    options:{
		      data:materiels
		    },
 		    labelAlign:'right', 
		    inputAlign:"right"
		  };
		   
  /* 选择机台多选下拉表 */
  var add_machine={
    view:"multiselect",
    id:"muls", 
    width:400,
    inputWidth:300,
    label:"机台组选择", 
    yCout:2,
    options:{
      data:machines.data 
    },
    labelAlign:'right', 
    inputAlign:"right"
  };
   
 
  
  /* 模态框头部信息 */
  var add_pro_toolbar={
    view:"toolbar",
    id:"add_pro_toolbar",
    elements:[     
      {view:"label", label: "添加工序",width:130},
      {},
      { view:"icon", icon:"times-circle", css:"alter",click:"cancel"}
    ], 
  }
  /* 弹出框图表按钮 */
  var right_button={
    type:"line",css:"right_button",rows:
    [
      {view:"button",value:"-->",width:50,disabled:true},
    ]
  };
  /* 模态框身体、尾部信息 */
  var add_pro_form = {
    view:"form",
    id:"add_pro_form",
    borderless:true,
    complexData:true,
    elements: [
      {
        cols:[
          pro_list,
          right_button, 
          {rows:[
            {
              cols:[
                {margin:0},
                add_materiel,
                add_button,
              ]  
            },   
            my_pro_dt,                           
          ]},
          right_button,
          {
            rows:[
            {height:230},
               add_machine,
              {
            	  view:"text",
                  id:"jump_value",
                  label:"跳动值",
                  placeholder:"集中装刀须填",
                  width:210
            	
              },{
            	  view:"text",
                  id:"clamp_length1",
                  label:"夹持长度1",
                  placeholder:"集中装刀须填",
                  width:210
              }
              ,{
            	  view:"text",
                  id:"clamp_length2",
                  label:"夹持长度2",
                  placeholder:"集中装刀须填",
                  width:210
              }
             ]
          }  
        ]
      },
      {
        margin:10,
        cols:[
          {},
          {view:"button",id:"btn_pro1",value:'上一步',inputWidth:70,width:70,click:'up_project'},
          {view:"button",id:"btn_pro2",value:'保存当前数据',inputWidth:120,width:120,click:'submit'},
          {view:"button",id:"btn_pro3",value:'完成',inputWidth:70,width:70,click:"all_submit"},
        ]
      }
    ]
  } 
  /* window模态框 */
  var process=new webix.ui({
    view:"window",
    id:'process',
    width:1800,
    position:"center",
    modal:true,
    move:true,
    head:webix.copy(add_pro_toolbar),
    body:webix.copy(add_pro_form)
  });
 // ---------------------- 添加工序-规格（寿命）-机台模态框结束------------------
  
  
//---------------------- 编辑项目模态框 start  --------------------------

  /* 显示工序添加操作 */
  var edit_pro_list={
    rows:[
      { margin:10,
        cols:[
          {
            view:"text",
            id:"edit_pro",
            label:"工序名称:",
            placeholder:"请输入工序名称",
            width:210
          },
          {
            view:"button",
            id:"edit_pros_btn",
            width:70,
            value:"添加工序",
            click:"edit_pros"
          }
        ]
      },
      {
        view:"text",
        id:"edit_search_pro",
        label:"快速查找:",
        placeholder:"请输入工序名称进行查询",
        width:270
      },
      {
        view:"list",         
        id:"edit_process_list",         
        template:"#process_name#<button class='delbtn11 right2 style'>删除</button>",
        width:270,
        height:400,
        select:true,
        columns:[{id:"process_id",header:"工序id",fillspace : true,hidden:true},],
        data:[],
        onClick: {// 删除工序事件
          "delbtn11": function(e, id, trg) {
            var list_index2=$$("edit_process_list").getIndexById(id);// 点击的删除按钮所在工序索引
            if (edit_xms2.process_data[list_index]) { // 判断数据是否已经保存过，若保存过还需将数据删除
              $$("edit_process_list").remove(id);// 删除相应界面
              edit_xms2.process_data.splice(list_index2,1); // 删除相应工序数据
              edit_ggss.splice(list_index2,1); // 删除相应规格寿命数据
              edit_jt_datas.splice(list_index2,1); // 删除相应机台数据
              /* 更换规格界面 */
              $$("edit_my_pro_dt").clearAll();
              var id2 = $$("edit_process_list").getSelectedId(); // 相应界面删除后，若焦点更换，获取其id
              var list_index3=$$("edit_process_list").getIndexById(id2);
              $$("edit_my_pro_dt").define("data",ggss[list_index3] );
              $$("edit_my_pro_dt").refresh();
              /* 更换机台界面 */           
              $$("edit_muls").setValue(jt_datas[list_index3]);
              $$("edit_muls").refresh();
            } 
            else {
              $$("edit_process_list").remove(id);
            }
            return false;
            // here it blocks default behavior
          }
        },
      }  
  ]};

  /* 规格表格 */
  var edit_my_pro_dt={
    view:"datatable",
    id:"edit_my_pro_dt",  
    width:530, 
    height:440, 
     columns:[
      {id:"material_id",header:"规格名称",width:220,type:"combo",options:cutters.data,suggest:{
        body:{
          on:{
            'onItemClick':function(id,e,node){
              // 获取整个工序的规格gg_values,并判断规格是否为重
              var dt=$$("edit_my_pro_dt");
              var sel2 = dt.getSelectedId();// 获取正在选择的行的行id,列id名称,和行id
              var row2 = dt.getItem(sel2.row);// 获取正在选择的行的行内容,列内容,和行id
              row2.cutter_code=id;
              
              var gg_value;
              var gg_values=[];
              var select_value=this.getItem(id).value;
              dt.eachRow( function (row){               
                gg_value=dt.getText(row,"material_id");
                gg_values.push(gg_value);                            
              });
              //
              for(var i = 0; i < gg_values.length; i++) {
                if(select_value==gg_values[i]){
                  webix.alert({
                    title:"警告",
                    text:"同一规格不能添加两次，如果需要添加，请在刀具库中添加新规格，通过客户简称区别！",
                    ok:"确定", 
                    type:"confirm-warning",
                    callback:function(result){
                      if(result==true){
                        var sel = dt.getSelectedId();// 获取正在选择的行的行id,列id名称,和行id
                        var row = dt.getItem(sel.row);// 获取正在选择的行的行内容,列内容,和行id
                        row.material_id="";
                        row.cutter_code="";
                        dt.updateItem(sel.row, row);                       
                      }
                    }
                  }); 
                  break;
                }
              };
            }
          }
        }
      }},
      {id:"edit_cutter_life",header:"寿命",editor:"text",width:70},
      {id:"cutter_code",header:"编码",width:150,hidden:true},
      {id:"cutter_id",header:"规格id",fillspace : true,hidden:true},
      {id:"edit_is_replace",header:"选为替换",width:100,checkValue:"1",template:"{common.checkbox()}"},
      {
          id: "edit_operate",
          header: "操作",
          width: 70,
          tooltip: false,
          fillspace: true,
          template: "<button class='delbtn21 style'>删除</button>"
      }/* {common.trashIcon()}删除 */
    ],  
    onClick: {// 删除规格寿命事件
      "delbtn21": function(e, id, trg) {// list_index指选中的工序
        var id2 = $$("edit_process_list").getSelectedId(); // 相应界面删除后，若焦点更换，获取其id
        var list_index=$$("edit_process_list").getIndexById(id2);// 焦点所在工序索引
        var list_index2=$$("edit_my_pro_dt").getIndexById(id);// 焦点所在规格寿命索引
        if (edit_xms2.process_data[list_index]) { // 判断数据是否已经保存过，若保存过还需将数据删除
      	  edit_ggss[list_index].splice(list_index2,1); // 删除相应规格寿命数据
          $$("edit_my_pro_dt").editStop();
          $$("edit_my_pro_dt").remove(id);    
        }
        else{
          $$("edit_my_pro_dt").editStop();
          $$("edit_my_pro_dt").remove(id); 
        }
        return false;
      } 
    },     
    select:true,
    data:"",
    editable:true,
    tooltip:true
  };

  /* 添加一行规格按钮 */
  var edit_add_button={
    view:"button",value:"添加物料",width:70,click:"edit_addRows"
  };
  var edit_materiel={
		    view:"multicombo",
		    id:"edit_materiels", 
		    width:300,
		    inputWidth:300,
		    yCout:2,
		    options:{
		      data:materiels
		    },
		    labelAlign:'right', 
		    inputAlign:"right"
		  };
		   
  
  /* 选择机台多选下拉表 */
  var edit_machine={
    view:"multiselect",
    id:"edit_muls", 
    width:230,
    inputWidth:200,
    label:"机台选择", 
    yCout:2,
    options:{
      data:machines.data 
    },
    labelAlign:'right', 
    inputAlign:"right"
  };

  /* 模态框头部信息 */
  var edit_pro_toolbar={
    view:"toolbar",
    id:"edit_pro_toolbar",
    elements:[     
      {view:"label", label: "编辑工序",width:130},
      {},
      { view:"icon", icon:"times-circle", css:"alter",click:"edit_cancel"}
    ], 
  }


  /* 模态框身体、尾部信息 */
  var edit_pro_form = {
    view:"form",
    id:"edit_pro_form",
    borderless:true,
    complexData:true,
    elements: [
      {
        cols:[
          edit_pro_list,
          right_button, 
          {rows:[
            {
              cols:[
                {},
                edit_materiel,
                edit_add_button
              ]  
            },   
            edit_my_pro_dt,                   
          ]},
          right_button,
          {
            rows:[
            {height:230},
              edit_machine   
            ]
          }  
        ]
      },
      {
        margin:10,
        cols:[
          {},
          {view:"button",id:"edit_btn_pro2",value:'保存当前数据',inputWidth:120,width:120,click:'edit_submit'},
          {view:"button",id:"edit_btn_pro3",value:'完成',inputWidth:70,width:70,click:"edit_all_submit"},
        ]
      }
    ]
  } 

  /* window模态框 */
  var edit_process=new webix.ui({
    view:"window",
    id:'edit_process',
    width:1400,
    position:"center",
    modal:true,
    move:true,
    head:webix.copy(edit_pro_toolbar),
    body:webix.copy(edit_pro_form)
  });
  //工序搜索功能
  $$("edit_search_pro").attachEvent("onTimedKeyPress",function(){
    var value = this.getValue();
    $$("edit_process_list").filter(function(obj){
      return obj.process_name.indexOf(value)>=0;
    })
  });
//---------------------- 编辑项目模态框 end  --------------------------
  
  /* 显示信息 */
  var my_template={
    template: "<span style='font-size:20px; font-weight:bold; color:#3498DB';>当前项目</span>&nbsp;/&nbsp;&nbsp;CurrentProject",
    height:45,
    width:300,
    borderless:true 
  };
  /* 创建项目按钮 */
  var my_button={
    cols:[
      {view:"button",id:"btn1",value:'创建项目',inputWidth:85,width:90,click:function(){showForm("project")}},
      {view:"button",id:"btn5",value:'编辑项目',inputWidth:85,width:90,click:"editProject"},
      {view:"button",id:"btn2",value:'删除项目',inputWidth:85,width:90,
        click: function() {
          var temp=$$('my_datatable3').getSelectedItem();
          var params = {};
          params["project_id"]=temp.project_id;
          webix.confirm({
            title:"警告",
            text:"确定删除该项目？",
            ok:"确定", 
            cancel:"取消",
            type:"confirm-warning",
            callback:function(result){
              if(result==true){
                webix.ajax().sync().post("delProject", params, function(text, xml, xhr) {
                  location.reload();
                })             
              }
            }
          });                
        }
      },
      {view:"button",id:"btn3",value:'保存修改',inputWidth:85,width:85,click: function() {
    	  webix.confirm({
  	        title:"提示",
  	        text:"确定要更新吗?更新之后项目相关生产排配信息也会随之更新。",
  	        ok:"确定", 
  	        cancel:"取消",
  	        callback:function(result){
  	        	if(result==true){
  	        			save();
  	        	}
  	        }
  	        });
      }
      },    
    ],   
  };
  /* 显示当前页面表格 */
  var my_datatable3={
    view:"datatable",
    id:"my_datatable3",
    columns:[
      { id:"project_id",header:"项目id",hidden:true},
      { id:"project_name",header:["项目名称",{ content:"textFilter", placeholder:"请输入项目名称进行查询",}],fillspace:true
  		,template : function(obj, type) {
  			return obj.project_name+"("+obj.start_date+" ~ "+obj.end_date+")"
		},  
      
      },
      { id:"process_name",header:"工序",fillspace:true,editor:"text"},
      { id:"process_id",header:"工序id",hidden:true},
      {id:"material_id",header:"物料编号",fillspace:true,hidden:true},
      {id:"customer_specs_no",header:"物料编号",fillspace:true},
      { id:"simple_specs_cust",header:"规格简称",fillspace:true},
      { id:"long_specs_cust",header:"规格全称",fillspace:true},

      { id:"cutter_life",header:"寿命",fillspace:true,editor:"text"},
      {id:"operate",header:"操作",fillspace:true,template:"<div><a href='#' onclick=\"edit('#project_id#','#process_id#','#material_id#');\">编辑</a></div>"}
    ],
    height:740,
    tooltip:true,
    data:{
      data:"",
      spans:[]
    },
    spans:true,
    select:"cell",
  };
  var web={
    type:"line",
    container:"body",
    id:"mylayout",
    rows:[
      my_template,      
      my_button,
      {height:10},
    ],
  };
  webix.ui(my_datatable3);
  webix.ui(web);
  /*---webix.ui结束----*/
  // 工序名搜索
  
  webix.ajax().sync().post("getNoStartProjectList", "", function(text, xml, xhr){
    var text1=JSON.parse(text); 
    var data = new webix.DataCollection({data:text1.data});
    $$('my_datatable3').data.sync(data);
    chuli(text1.data);
  });
  // 工序搜索功能
  $$("search_pro").attachEvent("onTimedKeyPress",function(){
    var value = this.getValue();
    $$("process_list").filter(function(obj){
      return obj.process_name.indexOf(value)>=0;
    })
  });
  /* 当数据保存后规格和寿命再更改 */
  $$('my_pro_dt').attachEvent("onAfterEditStop", function(state, editor, ignoreUpdate) {
      var material_judge2 = [];
      var life_judge2 = [];
      if (state.old == undefined || state.old == "") {
      } 
      else {
        if (state.value != state.old) {
          webix.alert({
                  title: "警告",
                  text: "您的规格或寿命数据已改，若该条数据之前已保存，请再次点击“保存当前数据”按钮，否则修改后的数据将无法保存后台！",
                  ok: "确定",
                  type: "confirm-warning",
                  callback: function(result) {
                      if (result == true) {
                      }
                  }
          });
        }
      }
  });
  
  /*------------------ 添加产能 start------------------------*/	
	var addYieldForm = [ 
	// 产能表格
	{
		view : "datatable",
		id : "tableA",
		editable : true,
		tooltip : true,
		height : 200
	}, {
		id:"save",
		view : "button",
		value : "确定",
		width : 80,
		click : "sure",
		css : {
			"margin-left" : "580px!important"
		}
	} ];
	var yieldHead = {
		view : "toolbar",
		margin : -4,
		cols : [ {
			view : "label",
			label : "录入产能，该项目下所有计划 将启用该产能"
		}]
	};
	var yieldBody = {
		view : "form",
		id : "form",
		autoheight : true,
		width : 700,
		margin : 20,
		elements : addYieldForm
	};
	webix.ui({
		view : "window",
		id : "win3",
		position : "center",
		modal : true,
		move : true,
		head : yieldHead,
		body : yieldBody
	});
  /*------------------ 添加产能 end------------------------*/	
	
  change();
  edit_change();
 /*--------------end-----------*/
  });
/* 显示模态框 */
function showForm(winId){
  $$(winId).show();
};
/* onAfterSelect更换规格和机台界面 */
function change(){
  $$("process_list").attachEvent("onAfterSelect",function(id,e,node){
    var plist=$$("process_list");
      list_index=plist.getIndexById(id);
      /* 更换规格界面 */
      $$("my_pro_dt").clearAll();
      $$("my_pro_dt").define("data",ggss[list_index] );
      $$("my_pro_dt").refresh();   
      /* 更换机台界面 */    
      // var text = $$("muls").getValue().replace(/\s/g, "");
      // $$("muls").setValue(jt_datas[list_index]);
      $$("muls").define("value",jt_datas[list_index]);
      $$("muls").refresh(); 
      
      
      $$("jump_value").define("value",jump_datas[list_index]);
      $$("jump_value").refresh(); 

      $$("clamp_length1").define("value",clamp_length_datas[list_index]);
      $$("clamp_length1").refresh(); 

      $$("clamp_length2").define("value",clamp_length2_datas[list_index]);
      $$("clamp_length2").refresh(); 

  });
}

/* onAfterSelect更换规格和机台界面 */
function edit_change(){
  $$("edit_process_list").attachEvent("onAfterSelect",function(id,e,node){
    var plist=$$("edit_process_list");
      list_index=plist.getIndexById(id);
      /* 更换规格界面 */
      $$("edit_my_pro_dt").clearAll();
      $$("edit_my_pro_dt").define("data",edit_ggss[list_index] );
      $$("edit_my_pro_dt").refresh();   
      /* 更换机台界面 */    
      $$("edit_muls").define("value",edit_jt_datas[list_index]);
      $$("edit_muls").refresh(); 
    });
}
/* 在添加项目页面点击“下一步”跳转入工序页面 */
function down_pro(){ 
  var data=$$("project_name").getValue();
  var start_date_data=$$("start_date").getValue();
  var end_date_data=$$("end_date").getValue();
  var bool=start_date_data<=end_date_data;
  if(data==""||start_date_data==""||end_date_data==""||bool==false){    
    webix.alert({
      title:"警告",
      text:"您有数据尚未填写！！<br/>或开始与结束日期存在逻辑错误！！",
      ok:"确定", 
      type:"confirm-warning",
      callback:function(result){
        if(result==true){
        }
      }
    });  
  }  
  else{
    $$('project').hide();
    showForm("process");
    /* 保存项目数据 */
    project_data=$$("add_P_form").getValues();
    project_data.operators = $$("operators").getValue();
   }     
}
/* 在添加工序、规格（寿命）、机台页面点击上一步跳转入添加项目页面 */
function up_project(){
  $$('process').hide();
  showForm("project");
}
/* 点击“添加工序”按钮添加一行工序并保存工序数据 */
function add_pros( ){  
  $$("add_pros_btn").disable();
  var pros=$$("process_list");
  var data=$$("add_pro").getValue();

  var gxmcs=[]; 
  var count=0;
  pros.data.each(function(obj){ 
    gxmcs.push(obj.process_name); 
  });
  for(var i=0;i<=gxmcs.length;i++){
    if(data==gxmcs[i]) count++;
  }
  if(data==""||count>0){
    webix.alert({
      title:"警告",
      text:"您输入的工序名称为空<br/>或该名称已存在！",
      ok:"确定", 
      type:"confirm-warning",
      callback:function(result){
        if(result==true){
        }
      }
    });  
    $$("add_pros_btn").enable();
  }
  else{
    var list_id=pros.add({
      process_name:data
    });
    $$('process_list').select(list_id);
    $$("add_pros_btn").enable();
  }     
};
/* 点击“添加规格”按钮添加一行规格名称和寿命 */
function addRows(){ 
  var dt=$$("my_pro_dt");  
    var item = $$("process_list").getSelectedItem();
    // 获取整个工序的规格gg_values,并判断规格是否为重 
    var dt=$$("my_pro_dt");
    var isNull = true;
    dt.eachRow( function (row){               
      var material_id_value = dt.getText(row,"material_id");
      if(material_id_value == ""){
    	  isNull = false;
    	  return;
      }           
    });
    if(!isNull){
    	alert("请填写规格为空行，在添加规格");
    	return;
    }
    if(item==undefined){
      dt.disable();
      webix.alert({
        title:"警告",
        text:"请先添加并在左侧工序列表中点击选择一项工序！",
        ok:"确定", 
        type:"confirm-warning",
        callback:function(result){
          if(result==true){
          }
        }
      }); 
    }
    else{
      dt.enable();
      var addCutters = [];
     var allCutters = JSON.parse($("#cutters").val());
   
      var gg_value;
      var gg_values=[];
     var changeMaterials =  $$("materiels").getValue().split(",")
    for (var j = 0; j < changeMaterials.length; j++) {
     for (var i = 0; i < allCutters.data.length; i++) {
		if(changeMaterials[j]==allCutters.data[i].customer_specs_no){		
			var addCutter={};
			var boo =  true;
			  dt.eachRow( function (row){
			         var gg_value=dt.getText(row,"material_id");
//			         console.log("gg_value");
//			         console.log(gg_value);
//			         console.log("allCutters");
//			         console.log(allCutters.data[i].material_id);
			          if(gg_value==allCutters.data[i].long_specs_cust){
			        	  boo=false;
			          }
 			  }); 
			  if(boo){  
		addCutter.material_id = allCutters.data[i].material_id;
		addCutter.cutter_life = 0;
		addCutters[addCutters.length] = addCutter;  
		var id = dt.add(addCutter);
	      dt.select(id);
	      dt.editRow(id);
		}
		}
		
     }
	}
   
    }
}
/* 获取机台数据 */
function gain_jt(){
  var gx = {
      "process_name": "",
      "cutters": [],
      "machines": []
  };
  var jts = [];
  var text;
  var type=typeof($$("muls").getValue());
  if(type=="string"){
    /* 机台ID的处理 */
    text = $$("muls").getValue().replace(/\s/g, "");
    var text1 = text.split(",");
    var ch=JSON.stringify(text1);
    var datas_muls=JSON.parse(ch);
    for(var i=0;i<datas_muls.length;i++){
      var jt = {
          "machine_id":""
        };
      jt.machine_id=datas_muls[i];
      jts.push(jt);
      gx.machines=jts;
    }
  }
  else if(type=="object"){
    text = $$("muls").getValue();
    for(var i=0;i<text.length;i++){
      var jt = {
          "machine_id":""
        };
      jt.machine_id=text[i];
      jts.push(jt);
      gx.machines=jts;
    }
  } 
  return gx.machines;
};
/* 获取规格、寿命数据 */
function gain_gg(){
  var gx = {
    "process_name": "",
    "cutters": [],
    "machines": []
  };
  var cutters = [];
  $$("my_pro_dt").eachRow( function (row){
    var gg = {
      "material_id":"",
      "cutter_life":"",
      "add_cutter_code":"",
      "is_replace":""
    };
    var dt=$$("my_pro_dt");
    gg.material_id=dt.getItem(row).material_id;
    gg.cutter_life=dt.getItem(row).cutter_life;
    gg.is_replace=dt.getItem(row).is_replace;
    gg.add_cutter_code=dt.getItem(row).add_cutter_code;
    cutters.push(gg);
    gx.cutters=cutters;
  });
  return gx.cutters;
};
/* 获取工序数据 */
function gain_gx(){  
  var gxs=[];
  var gxmcs=[];
  $$("process_list").data.each(function(obj){ 
    var gx = {
      "process_name": "",
      "cutters": [],
      "machines": [],
      "jump_value":"",
      "clamp_length1":"",
      "clamp_length2":""
    };
    gx.process_name=obj.process_name;  
    gxs.push(gx);   
  });
  return gxs;
};

function gain_jump(){
}

function gain_clamp1(){
	
}
function gain_clamp2(){
	
}
/* 获取项目数据 */
function gain_xm(){
  var xm = {
    "project_name": "",
    "project_code": "",
    "process_data": []
  };
  xm.project_name=project_data.project_name;
  xm.project_code=project_data.project_code;
  return xm;
};
/* 当点击完成页面的×时，提醒用户：最后一条数据尚未保存，是否退出该界面？ */
function cancel(){
  webix.confirm({
    title:"警告",
    text:"最后一条数据尚未保存，是否退出该界面？",
    ok:"退出",
    cancel:"返回",
    type:"confirm-warning",/* error */ 
    callback:function(result){
      if(result){
        $$('process').hide();
      }
    }
  });
}
/* 当点击“提交一条数据”时，提交一条数据到暂时变量xms2中保存 */
var ggss=[];// used
var xms2 = {// used
    "project_name": "",
    "project_code": "",
    "process_data": [   
    ]
  };
function edit(project_id,process_id,cutter_id){
	  if(project_id&&process_id&&cutter_id){
		  var dt=$$("my_datatable3");
		  dt.eachRow(function(row){
			if(dt.getItem(row).material_id==cutter_id&&dt.getItem(row).process_id==process_id&&dt.getItem(row).project_id==project_id){
			  dt.editRow(row);
			  dt.addRowCss(row, "newRow2");
			}
		  });
	  }

}
/* 将各个数据整合 */
function data(){
  var process_judge=[];
  var material_judge=[];
  var life_judge=[];
  var jts_judge=[];
  var material_nullValue=0;
  var life_nullValue=0;
  var jt_nullValue=0;
  /* 工序列表数据 */
  $$("process_list").data.each(function(obj){ 
    process_judge.push(obj.process_name);  
  });
  /* 规格表格数据 */
  $$("my_pro_dt").eachRow( function (row){
    var dt=$$("my_pro_dt");
    material_judge.push(dt.getItem(row).material_id);
    life_judge.push(dt.getItem(row).cutter_life);
  });
  /* 机台multiselect数据 */
  var text = $$("muls").getText().replace(/\s/g, "");
  var text1 = text.split(",");
  var ch=JSON.stringify(text1);
  jts_judge=JSON.parse(ch); 
  /* 使用material_nullValue记录规格名称数据的空值（""）数量 */
  for(var i=0;i<material_judge.length;i++){
    if(material_judge[i]==undefined||material_judge[i]==""){
      material_nullValue++;
    }    
  }
  /* 使用life_nullValue记录规格寿命数据的空值（""）数量 */
  for (var i = 0; i < life_judge.length; i++) {
    if(life_judge[i]==undefined||life_judge[i]==""){
      life_nullValue++;
    }   
  };
  /* 使用jt_nullValue记录机台数据的空值（""）数量 */
  for (var i = 0; i < jts_judge.length; i++) {
    if(jts_judge[i]==""||jts_judge[i]==undefined){
      jt_nullValue++;
    }   
  };
  /* 判断所有数据是否为空，一种空为没有添加（length为0），一种空为添加了但是没有内容（""） */
  if(process_judge.length<=0||material_judge.length<=0||material_nullValue>0||life_nullValue>0||jt_nullValue>0)
  {
    webix.alert({
      title:"警告",
      text:"当前数据存在空值，请检查工序、规格、机台！！",
      ok:"确定", 
      type:"confirm-warning",
      callback:function(result){
        if(result==true){
        }
      }
    });  
  }
  else{
    /* 工序数据 */
    var gxs2 = gain_gx();
    /* 规格、寿命数据 */
    var ggs2=gain_gg();  

    ggss[list_index]=ggs2;
        
    /* 机台数据 */
    var jts2 = gain_jt();   
    jtss[list_index]=jts2;


    /* 将规格数据传递给工序数据 */
    for(var i=0;i<gxs2.length;i++){
      gxs2[i].cutters=ggss[i];
    }
    
    /* 将机台数据传递给工序数据 */
    for(var i=0;i<gxs2.length;i++){
      gxs2[i].machines=jtss[i];
    }

    /* 项目数据 */
    xms2.project_name=project_data.project_name;
    xms2.project_code=project_data.project_code;
    xms2.project_code=project_data.project_code;

    xms2.start_date = project_data.start;
    xms2.end_date = project_data.end;
    xms2.redays = project_data.operators;
    /* 将工序数据传给项目 */
    xms2.process_data=gxs2;

    var jt_data=[];
    for(var i=0;i<jtss[list_index].length;i++){
      jt_data.push(jtss[list_index][i].machine_id);
    }
    jt_datas[list_index]=jt_data;  
    
    jump_datas[list_index]=$$("jump_value").getValue();
    clamp_length_datas[list_index]=$$("clamp_length1").getValue();
    clamp_length2_datas[list_index]=$$("clamp_length2").getValue();
    
    for(var i=0;i<gxs2.length;i++){
        gxs2[i].jump_value=jump_datas[i];
      }
    for(var i=0;i<gxs2.length;i++){
        gxs2[i].clamp_length1=clamp_length_datas[i];
      }
    for(var i=0;i<gxs2.length;i++){
        gxs2[i].clamp_length2=clamp_length2_datas[i];
      }
    /* 当点击“提交一条数据”按钮时，弹出可进行下一步添加数据操作提示框 */
    if(info==0){
      webix.alert({
        title: "提示信息",
        text: "当前工序数据已提交，您可以输入下一条数据，或更改上一条数据!",
        type:"'alert-warning'"
      });
    }
    /* 当点击“完成”按钮时，弹出提示框 */
    else if(info==1){
      /* 判断是否出现有工序名称，但没有工序规格和机台的情况，这种情况点击“提交一条数据”按钮事件无法判别 */
      var count=0;
      for(var i=0;i<xms2.process_data.length;i++){
        if(xms2.process_data[i].cutters==undefined){
          count++;
        }
      }
      if(count>0){
        webix.alert({
          title: "提示信息",
          text: "您有工序未添加规格或机台!",
          type:"'alert-warning'"
        });
      }
      else{
        $$('process').hide();
        var params ={};
        params.project_data = JSON.stringify(xms2);
         webix.ajax().sync().post("addProject", params, function(text, xml, xhr){
          alert("执行完毕");
          location.reload();
        }); 
      }
    }
  }
  $$("my_pro_dt").editStop(); 
}

function submit(){
  info=0;
  data(); 
}
function all_submit(){
	info=1; 
  data();	
 }
function callback2(data){
  $$("my_datatable3").define("url", "http://192.168.1.111:9001/Application/demo");
  $$("my_datatable3").refresh();
}
function sortNumber(propertyName1) {
    return function(object1, object2) {
        var value1 = object1[propertyName1];
        var value2 = object2[propertyName1];
        if(value1>value2){return 1;}
        else{
           if(value1<value2){return -1;}
           else{return 0;}
        }
        if (value1 > value2) {
            return 1;
        } 
        else if (value1 < value2) {
            return -1;
        } 
        else {
            return 0;
        }
    }
    ;
}
// 对后台的数据进行分析，几个项目，几个工序


function chuli(data){
  var data_project=data.sort(sortNumber("project_name"));// 按照条件项目名称排好序的所有数据
  var new_data=[];// 已经排好序的所有数据
  var start=data_project[0].project_name;// 相同组合的第一个数据的内容
  var j=0;// 相同组合的第一个数据的下标
  var temp_data1;// 存储在条件项目名称下再按照工序名称排好序的所有数据
  var begins=[];// 所有相同组合的第一个数据的下标的数组集合
  begins.push(0);
  var dt33=$$("my_datatable3");
  // -------start:在项目已排好的前提下将工序名称相同的数据排在一起-------------
  for(var i=0;i<data_project.length;i++){
    if(start!=data_project[i].project_name){
      temp_data1=data_project.slice(j,i).sort(sortNumber("process_name"));// 在条件项目名称下再按照工序名称排好序的所有数据
      j=i;
      begins.push(j);
      start=data_project[i].project_name;
      for(var n=0;n<temp_data1.length;n++){
        new_data.push(temp_data1[n]);
      }
    }   
  } 
  var temp_data2=data_project.slice(j).sort(sortNumber("process_name"));
  for(var k=0;k<temp_data2.length;k++){
    new_data.push(temp_data2[k]);
  }
  // -------end:在项目已排好的前提下将工序名称相同的数据排在一起-------------
  dt33.clearAll();
  dt33.define("data",new_data);
  dt33.refresh();
  // -------start:将相同的数据addSpan()在一起（项目名称）-------------
  for(var m=0;m<begins.length;m++){
    var e1=dt33.getIdByIndex(begins[m]);
    var result=begins[m+1]-begins[m];// 两个组合的第一个数据下标相减，得到第一个组合的长度
    if(begins[m+1]!=undefined){
      dt33.addSpan([[e1,"project_name",1,result]]);
    }
    else{// 最后一个组合的begins[i+1]为undefined
      var result2=new_data.length-begins[m];
      dt33.addSpan([[e1,"project_name",1,result2]]);
    }  
  }
  // -------end:将相同的数据addSpan()在一起（项目名称）-------------
  // -------start:将相同的数据addSpan()在一起（工序名称）-------------
  var start2=new_data[0].process_name;
  var s=0;
  var begins_1=begins;
  begins_1.push(new_data.length);
  var begins2=[];
  begins2.push(0);
  for(var g=1;g<begins_1.length;g++){
    for(var p=s;p<begins_1[g];p++){
      if(start2!=new_data[p].process_name){
        begins2.push(p);   
        start2=new_data[p].process_name;
      }
      
    }
    s=p;// 最后一个工序名称组合
    begins2.push(p);// 最后一个工序名称组合
    if(p<new_data.length){
      start2=new_data[p].process_name;
    }// 把最后一个多出来的下标去掉
  }
  var j2=0;
  for(var h=j2;h<begins2.length;h++){
    var e2=dt33.getIdByIndex(begins2[h]);
    j2=begins2[h+1];
    var result3=begins2[h+1]-begins2[h];// 两个组合的第一个数据下标相减，得到第一个组合的长度
    if(begins[h+1]==undefined&&e2==undefined){
      var result4=new_data.length-begins2[h];
      dt33.addSpan([[e2,"process_name",1,result4]]);
    }
    else{// 最后一个组合的begins[i+1]为undefined
      dt33.addSpan([[e2,"process_name",1,result3]]);
    }  
  }
  // -------end:将相同的数据addSpan()在一起（工序名称）-------------
  dt33.refresh();
}
 
function save(){
	var sb = new StringBuffer();
	 var dt=$$("my_datatable3");
     var params = {};
	 var flag = true;
	 if(flag){
	 dt.editStop();
	  dt.eachRow(function(row){
		  if(dt.hasCss(row,"newRow2")==true){
			 var  param=dt.getItem(row);
			  if(param.cutter_life==""){
				  alert("请填写刀具寿命...");
				  return false;
			  }
			  var str = JSON.stringify(param);
			  sb.append(str);
			  sb.append("&");
		         
		  }
    });
	  flag = false;
	  if(sb!=""){
		  params.jsonArr = sb.toString();
 		  webix.ajax().sync().post("updateProject", params, function(text, xml, xhr){
			  alert("执行完毕");
			  flag = true;
		  });
	  }else{
		  alert("未获取到修改内容...");
		  flag=true;
	  }
	 }
}




/* 当点击完成页面的×时，提醒用户：最后一条数据尚未保存，是否退出该界面？ */
function edit_cancel(){
  webix.confirm({
    title:"警告",
    text:"最后一条数据尚未保存，是否退出该界面？",
    ok:"退出",
    cancel:"返回",
    type:"confirm-warning",/* error */ 
    callback:function(result){
      if(result){
        $$('edit_process').hide();
      }
    }
  });
}

/* 点击“添加工序”按钮添加一行工序并保存工序数据 */
function edit_pros( ){  
  var pros=$$("edit_process_list");
  var data=$$("edit_pro").getValue();

  var gxmcs=[]; 
  var count=0;
  pros.data.each(function(obj){ 
    gxmcs.push(obj.process_name); 
  });
  for(var i=0;i<=gxmcs.length;i++){
    if(data==gxmcs[i]) count++;
  }
  if(data==""||count>0){
    webix.alert({
      title:"警告",
      text:"您输入的工序名称为空<br/>或该名称已存在！",
      ok:"确定", 
      type:"confirm-warning",
      callback:function(result){
        if(result==true){
        }
      }
    });  
  }
  else{
	$$('win3').show();
	var params = {};
	params.gongxu = data;
	webix.ajax().sync().post("getClassesList", params,
			function(text, xml, xhr) {
				var data = JSON.parse(text);
				columnD = data.tableHead;
				tableD = data.tableBodys;
			});
	$$('tableA').define("columns", columnD);
	$$('tableA').refresh();
	$$('tableA').clearAll();
	$$('tableA').define("data",tableD);
	$$("tableA").refresh();
	
    var list_id=pros.add({
      process_name:data
    });
    $$('edit_process_list').select(list_id);
  }     
};

/* 点击“添加规格”按钮添加一行规格名称和寿命 */
function edit_addRows(){ 
    var item = $$("edit_process_list").getSelectedItem();
    // 获取整个工序的规格gg_values,并判断规格是否为重 
    var dt=$$("edit_my_pro_dt");
    var isNull = true;
    dt.eachRow( function (row){               
      var material_id_value = dt.getText(row,"material_id");
      if(material_id_value == ""){
    	  isNull = false;
    	  return;
      }                   
    });
    if(!isNull){
    	alert("请填写规格为空行，在添加规格");
    	return;
    }
    if(item==undefined){
      dt.disable();
      webix.alert({
        title:"警告",
        text:"请先添加并在左侧工序列表中点击选择一项工序！",
        ok:"确定", 
        type:"confirm-warning",
        callback:function(result){
          if(result==true){
          }
        }
      }); 
    }
    else{
      dt.enable();
      var addCutters = [];
      var allCutters = JSON.parse($("#cutters").val());
      var gg_value;
      var gg_values=[];
      var changeMaterials =  $$("edit_materiels").getValue().split(",")
      for (var j = 0; j < changeMaterials.length; j++) {
      for (var i = 0; i < allCutters.data.length; i++) {
		if(changeMaterials[j]==allCutters.data[i].customer_specs_no){		
			var addCutter={};
			var boo =  true;
			  dt.eachRow( function (row){
			         var gg_value=dt.getText(row,"material_id");
//			         console.log("gg_value");
//			         console.log(gg_value);
//			         console.log("allCutters");
//			         console.log(allCutters.data[i].material_id);
			          if(gg_value==allCutters.data[i].long_specs_cust){
			        	  boo=false;
			          }
 			  }); 
			  if(boo){  
		addCutter.material_id = allCutters.data[i].material_id;
		addCutter.edit_cutter_life = 0;
		addCutters[addCutters.length] = addCutter;  
		var id = dt.add(addCutter);
	      dt.select(id);
	      dt.editRow(id);
		}
		}
		
	}
      }
    }
}

/* 获取工序数据 */
	function edit_gain_gx(){  
  var gxs=[];
  var gxmcs=[];
  $$("edit_process_list").data.each(function(obj){ 
    var gx = {
      "process_name": "",
      "process_id": "",
      "cutters": [],
      "machines": [],
      "status": 0
    };
    gx.process_name=obj.process_name;  
    gx.process_id=obj.process_id;  
    gxs.push(gx);   
  });
  return gxs;
};
/* 获取规格、寿命数据 */
function edit_gain_gg(){
  var gx = {
    "process_name": "",
    "cutters": [],
    "machines": []
  };
  var cutters = [];
  $$("edit_my_pro_dt").eachRow( function (row){
    var gg = {
      "material_id":"",
      "edit_cutter_life":"",
      "cutter_id":"",
      "cutter_code":"",
      "status": 0,
      "edit_is_replace":""
    };
    var dt=$$("edit_my_pro_dt");
    gg.material_id=dt.getItem(row).material_id;
    gg.edit_cutter_life=dt.getItem(row).edit_cutter_life;
    gg.edit_is_replace=dt.getItem(row).edit_is_replace;
    gg.cutter_id=dt.getItem(row).cutter_id;
    gg.cutter_code=dt.getItem(row).cutter_code;
    cutters.push(gg);
//    console.log(dt.row);
    gx.cutters=cutters;
  });
  return gx.cutters;
};
/* 获取机台数据 */
function edit_gain_jt(){
  var gx = {
      "process_name": "",
      "cutters": [],
      "machines": []
  };
  var jts = [];
  var text;
  var type=typeof($$("edit_muls").getValue());
  if(type=="string"){
    /* 机台ID的处理 */
    text = $$("edit_muls").getValue().replace(/\s/g, "");
    var text1 = text.split(",");
    var ch=JSON.stringify(text1);
    var datas_muls=JSON.parse(ch);
    for(var i=0;i<datas_muls.length;i++){
      var jt = {
          "machine_id":""
        };
      jt.machine_id=datas_muls[i];
      jts.push(jt);
      gx.machines=jts;
    }
  }
  else if(type=="object"){
    text = $$("edit_muls").getValue();
    for(var i=0;i<text.length;i++){
      var jt = {
          "machine_id":""
        };
      jt.machine_id=text[i];
      jts.push(jt);
      gx.machines=jts;
    }
  } 
  return gx.machines;
};

/* 将各个数据整合 */
function edit_data(){
  var process_judge=[];
  var material_judge=[];
  var life_judge=[];
  var jts_judge=[];
  var material_nullValue=0;
  var life_nullValue=0;
  var jt_nullValue=0;
  /* 工序列表数据 */
  $$("edit_process_list").data.each(function(obj){ 
    process_judge.push(obj.process_name);  
    
  });
  /* 规格表格数据 */
  $$("edit_my_pro_dt").eachRow( function (row){
    var dt=$$("edit_my_pro_dt");
    material_judge.push(dt.getItem(row).material_id);
    life_judge.push(dt.getItem(row).edit_cutter_life);
  });
  /* 机台multiselect数据 */
  var text = $$("edit_muls").getText().replace(/\s/g, "");
  var text1 = text.split(",");
  var ch=JSON.stringify(text1);
  jts_judge=JSON.parse(ch);
 
  /* 使用material_nullValue记录规格名称数据的空值（""）数量 */
  for(var i=0;i<material_judge.length;i++){
    if(material_judge[i]==undefined||material_judge[i]==""){
      material_nullValue++;
    }    
  }
  /* 使用life_nullValue记录规格寿命数据的空值（""）数量 */
  for (var i = 0; i < life_judge.length; i++) {
    if(life_judge[i]==undefined||life_judge[i]==""){
      life_nullValue++;
    }   
  };
  /* 使用jt_nullValue记录机台数据的空值（""）数量 */
  for (var i = 0; i < jts_judge.length; i++) {
    if(jts_judge[i]==""||jts_judge[i]==undefined){
      jt_nullValue++;
    }   
  };
  /* 判断所有数据是否为空，一种空为没有添加（length为0），一种空为添加了但是没有内容（""） */
  if(process_judge.length<=0||material_judge.length<=0||material_nullValue>0||life_nullValue>0)//||jt_nullValue>0
  {
    webix.alert({
      title:"警告",
      text:"当前数据存在空值，请检查工序、规格、机台！！",
      ok:"确定", 
      type:"confirm-warning",
      callback:function(result){
        if(result==true){
        }
      }
    });  
  }
  else{
    /* 工序数据 */
    var gxs2 = edit_gain_gx();
    /* 规格、寿命数据 */
    var ggs2 = edit_gain_gg();  

    edit_ggss[list_index]=ggs2;
        
    /* 机台数据 */
    var jts2 = edit_gain_jt();   
    edit_jtss[list_index]=jts2;
    
   
   
    // 获取产能
    var tableValues = "";
	$$("tableA").eachRow(function(row) {
		$$("tableA").editStop();
		// 遍历每一行，得到表格数据
		var rowObj = $$("tableA").getItem(row);
		tableValues += JSON.stringify(rowObj);
	});
	if(tableValues != ""){
		edit_cn[list_index] = JSON.parse(tableValues);
	}
	
	
	/* 将产能数据传递给工序数据 */
    for(var i=0;i<gxs2.length;i++){
	 if (typeof(gxs2[i].process_id) == "undefined") { 
		  gxs2[i].cn=edit_cn[i];
	  }else{
		  
	  }
    }
    
    /* 将规格数据传递给工序数据 */
    for(var i=0;i<gxs2.length;i++){
      gxs2[i].cutters=edit_ggss[i];
    }

    /* 将机台数据传递给工序数据 */
    for(var i=0;i<gxs2.length;i++){
      gxs2[i].machines=edit_jtss[i];
    }
    /* 项目数据 */
    edit_xms2.project_name=edit_project_data.project_name;
    edit_xms2.project_code=edit_project_data.project_code;
    /* 将工序数据传给项目 */
    edit_xms2.process_data=gxs2;

    var jt_data=[];
    for(var i=0;i<edit_jtss[list_index].length;i++){
      jt_data.push(edit_jtss[list_index][i].machine_id);
    }
   
    edit_jt_datas[list_index]=jt_data;
   
    /* 当点击“提交一条数据”按钮时，弹出可进行下一步添加数据操作提示框 */
    if(info==0){
      webix.alert({
        title: "提示信息",
        text: "当前工序数据已提交，您可以输入下一条数据，或更改上一条数据!",
        type:"'alert-warning'"
      });
      
    }
    /* 当点击“完成”按钮时，弹出提示框 */
    else if(info==1){
      /* 判断是否出现有工序名称，但没有工序规格和机台的情况，这种情况点击“提交一条数据”按钮事件无法判别 */
      var count=0;
      for(var i=0;i<edit_xms2.process_data.length;i++){
        if(edit_xms2.process_data[i].cutters==undefined){
          count++;
        }
      }
      if(count>0){
        webix.alert({
          title: "提示信息",
          text: "您有工序未添加规格或机台!",
          type:"'alert-warning'"
        });
      }
      else{
        $$('edit_process').hide();
        var params ={};
        // 和之前老项目对比，工序
		for(var i=0; i<projectOld.process_data.length; i++ ){  
			var pro_name_old = projectOld.process_data[i].process_name;
			var pro_id_old = projectOld.process_data[i].process_id;
			var rs = false;
			
			// 循环工序
			for(var k=0;k<edit_xms2.process_data.length;k++){
				var pro_name = edit_xms2.process_data[k].process_name;
				var pro_id = edit_xms2.process_data[k].process_id;
				if(pro_name_old == pro_name && pro_id_old == pro_id){
					rs = true;
					break;
				}
			}
			// 不存在工序 status=1
			if(!rs){
				var gx = {"process_name": "","process_id": "","status": 1};
	    	    gx.process_name = pro_name_old;  
	    	    gx.process_id = pro_id_old;  
	    	    edit_xms2.process_data.push(gx);
			}
			
			//和之前老项目对比：刀具规格
			for(var x=0;x<projectOld.process_data[i].cutters.length; x++){ //4
				for(var z=0;z<edit_xms2.process_data.length; z++){
					// 工序不相等退出本次循环
					if(pro_name_old != edit_xms2.process_data[z].process_name){
						continue;
					}
					// 状态为1退出本次循环
					if(edit_xms2.process_data[z].status == 1){
						continue;
					}
					var material_id_old = projectOld.process_data[i].cutters[x].material_id;
					var cutter_id_old = projectOld.process_data[i].cutters[x].id;
					var rs2 = false;
					
					// 循环刀具规格
					for(var y=0;y<edit_xms2.process_data[z].cutters.length;y++){
						var material_id = edit_xms2.process_data[z].cutters[y].material_id;
						var cutter_id = edit_xms2.process_data[z].cutters[y].cutter_id;
						if(material_id_old == material_id && cutter_id_old == cutter_id){
							rs2 = true;
							break;
						}
					}
					// 不存在刀具 status=1
					if(!rs2){
						var dj = {"material_id": "","cutter_id": "","status": 1};
						dj.material_id = material_id_old;  
						dj.cutter_id = cutter_id_old;  
			    	    edit_xms2.process_data[i].cutters.push(dj);
					}
				}
			}
		}
        
        params.project_data = JSON.stringify(edit_xms2);
        webix.ajax().sync().post("editProject", params, function(text, xml, xhr){
        	var res = JSON.parse(text);
        	if(res.ret == 1000){
        	 alert("执行完毕");
        	 location.reload();
         }else{
        	 alert("执行失败");
        	 location.reload();
         }
          
        }); 
      }
    }
  }
  $$("edit_my_pro_dt").editStop(); 
 
}

function edit_submit(){
	info=0;
	edit_data(); 
}
function edit_all_submit(){
	info=1; 
	edit_data();	
 }

// 点击编辑项目
function editProject(){
	var id = $$('my_datatable3').getSelectedId(); 
	if(typeof(id) == "undefined"){
		alert("请选择项目");
		return ;
	}
	edit_project_data.project_id = $$('my_datatable3').getItem(id).project_id;
	edit_project_data.project_name = $$('my_datatable3').getItem(id).project_name;
	
	var params ={"project_id": edit_project_data.project_id};
	
	webix.ajax().sync().post("getProjectById", params, function(text, xml, xhr){
		
		var rs = JSON.parse(text);
		if(rs.ret == "1"){
			projectOld = rs;
			$$("edit_process_list").clearAll();
			edit_xms2.project_id = rs.project_id;
			// 加载工序
			for(var i=0; i<rs.process_data.length; i++ ){
				var proVal = rs.process_data[i].process_name;
				var proIdVal = rs.process_data[i].process_id;
				info_pros(proVal,proIdVal);
				
				// 加载规格
				var cutters = [];
				for(var j=0; j<rs.process_data[i].cutters.length; j++ ){
					var material_id_val = rs.process_data[i].cutters[j].material_id;
					var cutter_life_val = rs.process_data[i].cutters[j].cutter_life;
					var cutter_id_val = rs.process_data[i].cutters[j].id;
					var cutter_code_val = rs.process_data[i].cutters[j].material_id;
					var edit_is_replace = rs.process_data[i].cutters[j].edit_is_replace;
 					var gg = {"material_id":"","edit_cutter_life":"","cutter_id":"","cutter_code":"","edit_is_replace":""};
					gg.material_id = material_id_val;
					gg.edit_cutter_life = cutter_life_val;
					gg.cutter_id = cutter_id_val;
					gg.cutter_code = cutter_code_val;
					gg.edit_is_replace = edit_is_replace;
					cutters.push(gg);	
				}
				info_addRows(cutters);
				
				// 加载机台
				var machines = [];
				for(var k=0; k<rs.process_data[i].machines.length; k++ ){
					var material_id_val = rs.process_data[i].machines[k].machine_id;
					var jt = {"machine_id":""};
					jt.gourp_id = material_id_val;
					machines.push(material_id_val);
				}
				info_addjt(machines);
				info=0;
				info_data(); 
			}
			
			showForm("edit_process");
		}else{
			alert("读取项目失败！");
		}
	}); 
}

function sure() {
	$$("save").disable();
	var tableValues = "";
	$$("tableA").eachRow(function(row) {
		$$("tableA").editStop();
		// 遍历每一行，得到表格数据
		var rowObj = $$("tableA").getItem(row);
		tableValues += JSON.stringify(rowObj);
	});
	var str = '""';
	if(tableValues.indexOf(str) > -1){
		alert("产能不为空");
	}else{
		$$('win3').hide();
	}
	$$("save").enable();
}

// 加载工序
function info_pros(proVal,proIdVal){  
  var pros = $$("edit_process_list");
  var data = proVal;
  var data2 = proIdVal;
  var gxmcs=[]; 
  var count=0;
  pros.data.each(function(obj){ 
    gxmcs.push(obj.process_name); 
  });
  for(var i=0;i<=gxmcs.length;i++){
    if(data==gxmcs[i]) count++;
  }
  var list_id=pros.add({
	  process_name:data,
	  process_id:data2
  });
  $$('edit_process_list').select(list_id);
};
// 加载规格
function info_addRows(cutters){ 
  $$("edit_my_pro_dt").clearAll();
  $$("edit_my_pro_dt").define("data",cutters);
  $$("edit_my_pro_dt").refresh();   
  
}
// 加载机台
function info_addjt(machines){
	/* 更换机台界面 */           
    $$("edit_muls").setValue(machines);
    $$("edit_muls").refresh();
}

/* 将各个数据整合 */
function info_data(){
  var process_judge=[];
  var material_judge=[];
  var life_judge=[];
  var jts_judge=[];
  var material_nullValue=0;
  var life_nullValue=0;
  var jt_nullValue=0;
  /* 工序列表数据 */
  $$("edit_process_list").data.each(function(obj){ 
    process_judge.push(obj.process_name);  
    
  });
  /* 规格表格数据 */
  $$("edit_my_pro_dt").eachRow( function (row){
    var dt=$$("edit_my_pro_dt");
    material_judge.push(dt.getItem(row).material_id);
    life_judge.push(dt.getItem(row).edit_cutter_life);
  });
 
  /* 使用material_nullValue记录规格名称数据的空值（""）数量 */
  for(var i=0;i<material_judge.length;i++){
    if(material_judge[i]==undefined||material_judge[i]==""){
      material_nullValue++;
    }    
  }
  /* 使用life_nullValue记录规格寿命数据的空值（""）数量 */
  for (var i = 0; i < life_judge.length; i++) {
    if(life_judge[i]==undefined||life_judge[i]==""){
      life_nullValue++;
    }   
  };
  /* 判断所有数据是否为空，一种空为没有添加（length为0），一种空为添加了但是没有内容（""） */
  if(process_judge.length<=0||material_judge.length<=0||material_nullValue>0||life_nullValue>0)//||jt_nullValue>0
  {
    webix.alert({
      title:"警告",
      text:"当前数据存在空值，请检查工序、规格、机台！！",
      ok:"确定", 
      type:"confirm-warning",
      callback:function(result){
        if(result==true){
        }
      }
    });  
  }
  else{
    /* 工序数据 */
    var gxs2 = edit_gain_gx();
    /* 规格、寿命数据 */
    var ggs2 = edit_gain_gg();  

    edit_ggss[list_index]=ggs2;
        
   /* 机台数据 */
    var jts2 = edit_gain_jt();   
    edit_jtss[list_index]=jts2;


    /* 将规格数据传递给工序数据 */
    for(var i=0;i<gxs2.length;i++){
      gxs2[i].cutters=edit_ggss[i];
    }

    /* 将机台数据传递给工序数据 */
    for(var i=0;i<gxs2.length;i++){
      gxs2[i].machines=edit_jtss[i];
    }
    /* 项目数据 */
    edit_xms2.project_name=edit_project_data.project_name;
    edit_xms2.project_code=edit_project_data.project_code;
    /* 将工序数据传给项目 */
    edit_xms2.process_data=gxs2;

    var jt_data=[];
        for(var i=0;i<edit_jtss[list_index].length;i++){
      jt_data.push(edit_jtss[list_index][i].machine_id);
    }
  
    edit_jt_datas[list_index]=jt_data;
   
  }
  
  $$("edit_my_pro_dt").editStop(); 
 
}
